<html>
<head>
<script type="text/javascript" src="/_ah/channel/jsapi"></script>
<script type="text/javascript">
var ws;
function init() {
  console.log("init.");
  var mail = document.getElementById("mail");
  var status = document.getElementById("status");
  var numClients = 0;
  var numSenders = 0;
  function onOpen() {
     status.innerText = "connected";
  };
  function onClose() {
     status.innerHTML = "connection closed";
  };

  function updateStatus() {
     status.innerHTML = "connected<br>(" + numClients + " browsers, " + numSenders + " SMTP clients)";
     return;
  }

  function onMessage(e) {
     var m = JSON.parse(e.data);
     if (m.NumClients != null) {
         numClients = m.NumClients;
         updateStatus();
         return;
     }
     if (m.NumSenders != null) {
         numSenders = m.NumSenders;
         updateStatus();
         return;
     }
     console.log(m);
     var md = document.createElement("div");
     md.innerHTML = "<table>" +
		"<tr class='from'><th>From:</th><td>" + m.From + " <i>[could be fake]</i></td></tr>" +
		"<tr class='to'><th>To:</th><td>"+m.To+"</td></tr>" +
		"<tr class='subject'><th>Subject:</th><td>" + m.Subject + "</td></tr>" +
		"<tr class='body'><th>Body:</th><td>" + m.Bodies + "</td></tr>" +
                "</table>";
     mail.insertBefore(md, mail.firstChild)
  };

  function connect() {
    if (ws != null) {
       ws.close();
       ws = null;
    }
    status.innerText = "connecting...";
    var url = "ws://websomtep.danga.com/stream";
    channel = new goog.appengine.Channel('{{ token }}');
    ws = channel.open();
    ws.onopen = onOpen;
    ws.onclose = onClose;
    ws.onmessage = onMessage;
  }
  connect();
}
</script>
<style>
body {
	font-family: Futura;
}
#about {
	float: right;
	width: 350px;
	padding: 10px;
	border: 1px solid black;
}
#status {
	padding: 10px;
	margin-bottom: 1em;
}
#mail table {
	margin-bottom: 1em;
}
#mail table th,
#mail table td {
	vertical-align: top;
	text-align: left;
}
</style>
</head>
<body onLoad="init();">
<div id="about">
<p>This is an email receiver written in <a href="http://https://developers.google.com/appengine/docs/python/overview/">Python for App Engine</a> which streams incoming mail to your (and everybody else's) active Channel API connection.</p>
<p>Test it! Email <a href="mailto:whatever@aemailstream.appspotmail.com"><i>whatever</i>@aemailstream.appspotmail.com</a> (protip: images don't yet work, because Moishe hasn't written the code to wire them up yet)</p>
<p>Any browser will work, no need for a browser that supports websockets.</p>
<p>Source code is here: <a href="https://github.com/Moishe/aemailstreamer">https://github.com/Moishe/aemailstreamer</a>.</p>
</div>
<h1>aemailstreamer = Streaming inbound mail over the Channel API</h1>
<div id="status"></div>
<div id="mail"></div>
</body>
</html>
